package cn.guo.algorithm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 数组工具类
 * Created by guo on 2015/10/19.
 */
public  class AlgorithmUtils {

    /**
     * 线程打印数组
     * @param arr
     */
     public static void asyncPrintMsg(final String arr){

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized(AlgorithmUtils.class) {
                    System.out.println(arr);
                }
            }
        }).start();
    }

    /**
     * 线程打印数组
     * @param arr
     */
    public static void asyncPrintArrayList(List<Integer> arr){
        final List<Integer> dest = new ArrayList<Integer>(arr.size());
        dest.addAll(arr);
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized(AlgorithmUtils.class) {
                    for (int i : dest) {
                        System.out.print(i + ",");
                    }
                    System.out.print("/////\n");
                }
            }
        }).start();
    }

    /**
     * 错误的做法！耗时长
     * 获取随机数
     * @param count
     * @return
     */
    private static List<Integer> getRandomList(int count) {
        List<Integer> arr = new ArrayList<Integer>();
        while (arr.size() < count) {
            int random = (int) (Math.random() * count);
            if (arr.indexOf(random) == -1) {
                arr.add(random);
                //System.out.print(random + ",");
            }
        }
        //System.out.print("\n");
        return arr;
    }

    /**
     * 获取随机数
     * @param count
     * @return
     */
    public static List<Integer> getRandomList2(int count) {
        List<Integer> arr = new ArrayList<Integer>();
        //创建数组
        for (int i = 0; i < count; i++) {
            arr.add(i);
        }
        //打乱数组顺序
        for(int i=0;i<arr.size();i++){
            int index = (int)(Math.random()*arr.size());
            int j = arr.get(index);
            int k = arr.get(0);
            arr.set(0,j);
            arr.set(index,k);
        }

        return arr;
    }
}
